import React, { createContext, useCallback, useContext, useState } from "react";
import { getCommonEventList, getEventList } from "../services/index";

interface CategoryContextData {
  categorys: any[];
  commonCategorys: any[];
  loadCategory: () => Promise<void>;
  loadCommonCategory: () => Promise<void>;
  selectedCategoryId: any;
  selectedCategoryString: any;
  updateSelectedCategoryId: (d: any) => void;
  resetSelected: boolean;
  updateResetSelected: (d: boolean) => void;
  selectedStatus: boolean;
  updateSelectedStatus: (d: boolean) => void;
}

const CategoryContext = createContext({} as CategoryContextData);

interface CategoryProviderProps {
  children: React.ReactNode;
}

export const CategoryProvider: React.FC<CategoryProviderProps> = ({
  children,
}) => {
  const [selectedCategoryId, setCategorySelectedId] = useState(null);
  const [selectedCategoryString, setCategorySelectedString] = useState("");

  const [categorys, setCategorys] = useState([]);
  const [commonCategorys, setCommonCategorys] = useState([]);

  const [selectedStatus, setSelectedStatus] = useState(true);
  const [resetSelected, setResetSelected] = useState(false);


  async function loadCategory() {
    updateResetSelected(true);
    const datas = await getEventList();
    setCategorys(datas.data);
  }

  async function loadCommonCategory() {
    const datas = await getCommonEventList();
    setCommonCategorys(datas.data);
  }

  const updateSelectedCategoryId = useCallback(
    (d) => {
      setCategorySelectedId(d);
    },
    [setCategorySelectedId]
  );

  const updateSelectedStatus = useCallback(
    (d) => {
      setSelectedStatus(d);
    },
    [setSelectedStatus]
  );

  const updateResetSelected = useCallback(
    (d) => {
      setResetSelected(d);
    },
    [setResetSelected]
  );

  return (
    <CategoryContext.Provider
      value={{
        categorys,
        commonCategorys,
        loadCategory,
        loadCommonCategory,
        selectedCategoryId,
        selectedCategoryString,
        updateSelectedCategoryId,
        selectedStatus,
        updateSelectedStatus,
        resetSelected,
        updateResetSelected,
      }}
    >
      {children}
    </CategoryContext.Provider>
  );
};

export function useCategory() {
  const context = useContext(CategoryContext);

  if (!context) throw new Error("useTasks must be used inside a sProvider");

  return context;
}
